const Sequelize = require("sequelize");
const sizeOf = require("image-size");
const path = require("path");
const fs = require("fs");
const AWS = require("aws-sdk");
const clientSecretKey = "NunWQnRIyFFayqghlzoMF0xlAEsKdTEctaI+Tcoc";
// These two keys are only needed if you plan on using the AWS SDK
const serverPublicKey = "AKIAOUX2AD3PLYU5NO5Q";
const serverSecretKey = "IpM7Q7v58B2G4mki2xIeizLO+cZkV9sz+2VoP3lB";
// Set these two values to match your environment
const expectedBucket = "testimageupload";
const expectedHostname = "testimageupload.s3.cn-northwest-1.amazonaws.com.cn";

// Init S3, given your server-side keys.  Only needed if using the AWS SDK.
AWS.config.update({
  accessKeyId: serverPublicKey,
  secretAccessKey: serverSecretKey,
  region: "cn-northwest-1" // region of your bucket
});

var s3 = new AWS.S3();

const POSTGRES_CONNECTION_STRING =
  process.env.POSTGRES_CONNECTION_STRING ||
  "postgres://postgres:password@localhost:6432/postgres";

async function upload(fields, files) {
  return new Promise(function(resolve, reject) {
    //做一些异步操作
    try {
      var sequelize = new Sequelize(POSTGRES_CONNECTION_STRING, {});
      //get file //既处理表单，又处理文件上传
      //设置文件上传文件夹/路径，__dirname是一个常量，为当前路径
      let oldPath = files.file.path; //这里的路径是图片的本地路径
      var dimensions = sizeOf(oldPath);
      let name = files.file.name;
      //这里我传回一个下载此图片的Url
      fs.readFile(oldPath, (err, data) => {
        if (err) throw err;
        const params = {
          Bucket: expectedBucket, // pass your bucket name
          ACL: "public-read",
          Key: name, // file will be saved as testBucket/contacts.csv
          Body: data
        };
        s3.putObject(params, async function(s3Err, data) {
          if (s3Err) reject(s3Err);

          var res = await sequelize.query(
            "BEGIN;" +
              "INSERT INTO dataset_item( dataset_id, name, is_folder, path, real_name, size, metadata, create_by) values (:datasetId, :name, :isFolder, :path, :name, :size, :metadata, :createBy); " +
              "COMMIT;",
            {
              replacements: {
                datasetId: fields.did,
                name: name,
                isFolder: false,
                size: fields.size,
                path: "",
                metadata: JSON.stringify({
                  width: dimensions.width,
                  height: dimensions.height
                }),
                createBy: fields.uid
              }
            }
          );
          sequelize.close();
          //update database
          resolve({ status: "success", name: name });
        });
      });
      //})
      //upload to s3

      //create dataset item

      //fetch team members
    } catch (e) {
      console.log(e);
      sequelize.close();
      reject(e);
    }
  });
}

module.exports.upload = upload;
